package cn.zero.letaomallspringboot.service.impl;

import cn.zero.letaomallspringboot.common.PageResult;
import cn.zero.letaomallspringboot.common.IdGenerator;
import cn.zero.letaomallspringboot.entity.Good;
import cn.zero.letaomallspringboot.mapper.GoodMapper;
import cn.zero.letaomallspringboot.service.IGoodService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class GoodService implements IGoodService {

    private final GoodMapper goodMapper;

    private static final Logger logger = LoggerFactory.getLogger(GoodService.class);

    public GoodService(GoodMapper goodMapper) {
        this.goodMapper = goodMapper;
    }

    public PageResult<Good> goodList(Map<String, Object> params) {
        // 提取分页参数，确保非 null
        int page = params.containsKey("page") ? (int) params.get("page") : 1;
        int size = params.containsKey("size") ? (int) params.get("size") : 10;
        int offset = (page - 1) * size;

        // 提取搜索参数（允许 null）
        String name = params.containsKey("name") ? (String) params.get("name") : null;
        String shopName = params.containsKey("shopName") ? (String) params.get("shopName") : null;
        String goodType = params.containsKey("goodType") ? (String) params.get("goodType") : null;

        // 日志调试（生产环境可移除）
        logger.info("分页查询参数: page={}, size={}, offset={}, name={}, shopName={}, goodType={}",
                page, size, offset, name, shopName, goodType);

        // 查询分页数据
        List<Good> list = goodMapper.selectByPage(offset, size, name, shopName, goodType);

        // 查询总条数
        long total = goodMapper.selectCount(name, shopName, goodType);

        return new PageResult<>(list, total);
    }

    @Transactional
    public boolean addGood(Good good) {
        // 生成 9~10 位纯数字 ID（比如 873514965）
        good.setGoodId(IdGenerator.nextId());

        good.setExist(1);
        good.setStock(good.getStock() == null ? 0 : good.getStock());

        Date now = new Date();
        good.setAddTime(now);
        good.setUpdateTime(now);

        return goodMapper.insertSelective(good) > 0;
    }

    public boolean updateGood(Good good) {
        // 如果是修改，不生成新ID；如果是复制新增，才生成
        if (good.getGoodId() == null) {
            good.setGoodId(IdGenerator.nextId());
        }
        good.setUpdateTime(new Date());
        return goodMapper.updateByPrimaryKeySelective(good) > 0;
    }

    public boolean deleteGood(Integer id) {
        return goodMapper.deleteByPrimaryKey(id) > 0;
    }

    public boolean batchDeleteGood(List<Integer> ids) {
        return goodMapper.batchDeleteByIds(ids) > 0;
    }

    public Good getGood(Integer id) {
        return goodMapper.selectByPrimaryKey(id);
    }
}